package test;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

import jeasy.analysis.MMAnalyzer;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.index.CorruptIndexException;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.store.LockObtainFailedException;

public class IndexProcesser {
	
	private static String INDEX_PATH = "西行漫记index";
	/**
	 * @param args
	 * @throws IOException 
	 * @throws LockObtainFailedException 
	 * @throws CorruptIndexException 
	 */
	public static void indexCreate(String path) throws CorruptIndexException, LockObtainFailedException, IOException {
		// TODO Auto-generated method stub
		IndexWriter writer = new IndexWriter(INDEX_PATH,new MMAnalyzer(), true);
		File fileDir = new File(path);
		File[] fileList = fileDir.listFiles();
		for (int i = 0;i<fileList.length;i++){
			String fileName = fileList[i].getName();
			if (fileName.substring(fileName.lastIndexOf(".")).equals(".txt")){
				Document doc = new Document();
				Field field = new Field("filename",fileList[i].getName(),Field.Store.YES,Field.Index.TOKENIZED);
				doc.add(field);
				field = new Field("content",loadFileToString(fileList[i]),Field.Store.NO,Field.Index.TOKENIZED);
				doc.add(field);
				writer.addDocument(doc);
				
				
			}
			
		}
		writer.close();

	}
	private static String loadFileToString(File file) throws IOException {
		// TODO Auto-generated method stub
		BufferedReader br = new BufferedReader(new FileReader(file));
		StringBuffer sb = new StringBuffer();
		String line = br.readLine();
		while (line!=null){
			sb.append(line);
			line = br.readLine();
		}
		br.close();
		return sb.toString();

	}
	
	public static void main(String [] args) throws CorruptIndexException, LockObtainFailedException, IOException{
		IndexProcesser ip = new IndexProcesser();
		ip.indexCreate("西行漫记");
	}

}
